package BinaryTree;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/*
* 二叉树的序列化与反序列化
* */
public class Offer37serialize {
    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        return reserialize(root,"");
    }

    private String reserialize(TreeNode root, String s) {
        if(root==null){
            s+="None,";
        }else{
            s+=s.valueOf(root.val)+",";
            s=reserialize(root.left,s);
            s=reserialize(root.right,s);
        }
        return s;

    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        String[] split = data.split(",");
//        List<String> list = Arrays.asList(split);
        List<String> list = new LinkedList<>(Arrays.asList(split));
        return rederialize(list);
    }

    private TreeNode rederialize(List<String> list) {
        if(list.get(0).equals("None")){
            list.remove(0);
            return null;
        }
        TreeNode node = new TreeNode(Integer.valueOf(list.get(0)));
        list.remove(0);
        node.left=rederialize(list);
        node.right=rederialize(list);

        return node;

    }
}
